<template>
    <n-tooltip trigger="hover">
        <template #trigger>
            <n-cascader
                placeholder="请选择城市"
                filterable
                cascade
                :clearable="prop.clear"
                :style="{ width: '100%' }"
                :check-strategy="prop.prov ? 'parent' : 'child'"
                :options="opts"
                @update:value="doChange"
                label-field="n"
                value-field="c"
                children-field="s"
            >
                <template #action>
                    <span>点击</span>
                    <n-button text @click="execLoad">更新城市数据</n-button>
                </template>
            </n-cascader>
        </template>
        {{ tips || '请选择城市' }}
    </n-tooltip>
</template>

<script lang="ts" setup>
import { ref, onBeforeMount, onMounted } from 'vue'

import { Http } from '@/libs'

const prop = defineProps({
    prov: {
        type: Boolean,
        default: false,
    },
    clear: {
        type: Boolean,
        default: false,
    },
    tip: {
        type: String,
        default: '',
    },
})

const tips = ref<string>('')

const emit = defineEmits(['update:value'])

const doChange = (vals: any, opt: any) => {
    tips.value = opt ? opt.n : undefined
    emit('update:value', vals)
}

const opts = ref([])

const execLoad = () => {
    Http.post('/comm/data/district', { level: 2 }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        opts.value = resp.data.items
        localStorage.setItem('Cache.Citys.Tree', JSON.stringify(resp.data.items))
    })
}

onBeforeMount(() => {
    let cache = localStorage.getItem('Cache.Citys.Tree')
    if (cache != '' && cache != null) {
        opts.value = JSON.parse(cache)
    } else {
        execLoad()
    }
})
onMounted(() => {})
</script>
